<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    {#    <script src="dist/src/cos.js" type="text/javascript" charset="utf-8"></script>#}
    <script src="/static/dist/cos-js-sdk-v5.min.js"></script>

</head>
<body>
<input type="file" id="file-selector">
<input id="submitBtn" type="submit" value="上传">


<script>
    var Bucket = 'sass-1300980145';
    var Region = 'ap-beijing';
    var selectedFile;
    var filename;
    $("#file-selector").change(function () {
        selectedFile = document.getElementById('file-selector').files[0];
        filename = selectedFile.name;
    });


    var Bucket = 'sass-1300980145';
    var Region = 'ap-beijing';
    var protocol = location.protocol === 'https:' ? 'https:' : 'http:';
    var prefix = protocol + '//' + Bucket + '.cos.' + Region + '.myqcloud.com/';
    var camSafeUrlEncode = function (str) {
        return encodeURIComponent(str)
            .replace(/!/g, '%21')
            .replace(/'/g, '%27')
            .replace(/\(/g, '%28')
            .replace(/\)/g, '%29')
            .replace(/\*/g, '%2A');
    };
    // 计算签名
    var getAuthorization = function (options, callback) {
        var url = 'http://127.0.0.1:8000/app02/send';
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.onload = function (e) {
            var credentials;
            try {
                credentials = (new Function('return ' + xhr.responseText))().credentials;
            } catch (e) {
            }
            if (credentials) {
                callback(null, {
                    XCosSecurityToken: credentials.sessionToken,
                    Authorization: CosAuth({
                        SecretId: credentials.tmpSecretId,
                        SecretKey: credentials.tmpSecretKey,
                        Method: options.Method,
                        Pathname: options.Pathname,
                    })
                });
            } else {
                console.error(xhr.responseText);
                callback('获取签名出错');
            }
        };
        xhr.onerror = function (e) {
            callback('获取签名出错');
        };
        xhr.send();
    };


    var uploadFile = function (file, callback) {
        var Key = 'dir/' + file.name; // 这里指定上传目录和文件名
        getAuthorization({Method: 'PUT', Pathname: '/' + Key}, function (err, info) {

            if (err) {
                alert(err);
                return;
            }
            var auth = info.Authorization;
            var XCosSecurityToken = info.XCosSecurityToken;
            var url = prefix + camSafeUrlEncode(Key).replace(/%2F/g, '/');
            var xhr = new XMLHttpRequest();
            xhr.open('PUT', url, true);
            xhr.setRequestHeader('Authorization', auth);
            XCosSecurityToken && xhr.setRequestHeader('x-cos-security-token', XCosSecurityToken);
            xhr.upload.onprogress = function (e) {
                console.log('上传进度 ' + (Math.round(e.loaded / e.total * 10000) / 100) + '%');
            };
            xhr.onload = function () {
                if (xhr.status === 200 || xhr.status === 206) {
                    var ETag = xhr.getResponseHeader('etag');
                    callback(null, {url: url, ETag: ETag});
                } else {
                    callback('文件 ' + Key + ' 上传失败，状态码：' + xhr.status);
                }
            };
            xhr.onerror = function () {
                callback('文件 ' + Key + ' 上传失败，请检查是否没配置 CORS 跨域规则');
            };
            xhr.send(file);
        });
    };

    // 监听表单提交
    document.getElementById('submitBtn').onclick = function (e) {
        console.log('222');
        var file = document.getElementById('file-selector').files[0];
        if (!file) {
            document.getElementById('msg').innerText = '未选择上传文件';
            return;
        }
        file && uploadFile(file, function (err, data) {
            console.log(err || data);
            document.getElementById('msg').innerText = err ? err : ('上传成功，ETag=' + data.ETag);
        });
    };


</script>

</body>
</html>